package org.dromara.learning_xq.config;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.dromara.learning_xq.exetion.BadRequestException;
import org.dromara.learning_xq.exetion.CommonConstants;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.UUID;

/**
 *
 * 七牛云上传删除Utils
 *
 * @Author zhangzikang
 * @Date 2023/8/13 8:54
 */
@org.springframework.context.annotation.Configuration
public class QiniuUtil {

    /**
     *
     * qiniu:
     *   accessKey: RN70atSgjEj8OczW5NSuYJt1hITzAqUz_4PlmQui
     *   secretKey: Kk34qL0hHtDmlPGcXDm9U-sGO7GU3huGQFPjjVy6
     *   bucket: lecturer-plus
     *   path: http://s2e7ux0ha.hb-bkt.clouddn.com
     *
     */

        // 七牛云的accessKey
    private static String accessKey = "bia0cM3uFDJ69kx_tzT255eeyNjQ2EomQuv5nKaT";

    // 七牛云的secretKey
    private static String secretKey = "_EhxA9ZRNm-JjR7Q6IdxdQeIOziG_v9A9xKTy3Fq";

    // 七牛云的存储空间名称
    private static String bucket = "lspsb";

    // 七牛云的存储空间链接
    private static String path = "sik9liyvq.hb-bkt.clouddn.com";


 /*   *//**
     * 上传资料
     * @param file 资料
     * @return 返回资料路径
     * @Author zhangzikang
     * @Date 2023/8/13 8:54
     * @throws Exception
     *//*
    public String uploadInformation(MultipartFile file) throws Exception{
        // 判断文件是否为空
        if(file.isEmpty()) {
            throw new BadRequestException(CommonConstants.FileIsEmpty);
        }
        //获取文件后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //允许上传的文件格式集合
        String[] suffixes = new String[]{".zip"};
        boolean bool = false;
        //判断格式是否在suffixes中
        for(String string : suffixes){
            if (string.equalsIgnoreCase(suffix)){
                bool = true;
                break;
            }
        }
        if(!bool){
            throw new BadRequestException(CommonConstants.FormatError);
        }
        return getFile(suffix, file);
    }

    *//**
     * 上传视频
     * @param file 视频
     * @return 返回视频路径
     * @Author zhangzikang
     * @Date 2023/8/13 8:54
     * @throws Exception
     */
    public String uploadVideo(MultipartFile file) throws Exception{

        // 判断文件是否为空
        if(file.isEmpty()) {
            throw new BadRequestException(CommonConstants.FileIsEmpty);
        }
        //获取文件后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //判断格式是否正确
        if(!suffix.equalsIgnoreCase(".mp4")){
            throw new BadRequestException(CommonConstants.FormatError);
        }
        return getFile(suffix, file);
    }

    /**
     * 上传简介
     * @param file 简介
     * @return 返回简介路径
     * @Author zhangzikang
     * @Date 2023/8/13 8:54
     * @throws Exception
     *//*
    public String uploadSynopsis(MultipartFile file) throws Exception{

        // 判断文件是否为空
        if(file.isEmpty()) {
            throw new BadRequestException(CommonConstants.FileIsEmpty);
        }

        //获取文件后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //允许上传的文件格式集合
        String[] suffixes = new String[]{".doc", ".docx", ".docx"};
        boolean bool = false;
        //判断格式是否在suffixes中
        for(String string : suffixes){
            if (string.equalsIgnoreCase(suffix)){
                bool = true;
                break;
            }
        }
        if(!bool){
            throw new BadRequestException(CommonConstants.FormatError);
        }
        return getFile(suffix, file);
    }*/

    /**
     * 上传图片到七牛云
     * @param file 图片
     * @return 返回图片存储后的新图片名
     * @Author zhangzikang
     * @Date 2023/8/13 8:54
     * @throws Exception
     */
/*    public String uploadImage(MultipartFile file) throws Exception{

        // 判断图片是否为空或图片大小是否大于限制
        if(file.isEmpty()) {
            throw new BadRequestException(CommonConstants.FileIsEmpty);
        }else if(file.getSize() > CommonConstants.imgSize){
            throw new BadRequestException(CommonConstants.imageSize);
        }
        //获取图片后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //允许上传的图片格式集合
        String[] suffixes = new String[]{".jpeg", ".jpg", ".png"};
        boolean bool = false;
        //判断格式是否在suffixes中
        for(String string : suffixes){
            if (string.equalsIgnoreCase(suffix)){
                bool = true;
                break;
            }
        }
        if(!bool){
            throw new BadRequestException(CommonConstants.FormatError);
        }
        // 上传图片并返回路径
        return getFile(suffix, file);
    }*/
    public String uploadImage(MultipartFile file) throws Exception {
        // 判断图片是否为空或图片大小是否大于限制
        if (file.isEmpty()) {
            throw new BadRequestException(CommonConstants.FileIsEmpty);
        } else if (file.getSize() > CommonConstants.imgSize) {
            throw new BadRequestException(CommonConstants.imageSize);
        }
        // 获取图片后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 允许上传的图片格式集合
        String[] suffixes = new String[]{".jpeg", ".jpg", ".png"};
        boolean bool = false;
        // 判断格式是否在suffixes中
        for (String string : suffixes) {
            if (string.equalsIgnoreCase(suffix)) {
                bool = true;
                break;
            }
        }
        if (!bool) {
            throw new BadRequestException(CommonConstants.FormatError);
        }
        // 上传图片并返回路径
        return getFile(suffix, file);
    }

    public String getFile(String suffix, MultipartFile file) throws IOException, BadRequestException {
        // 构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2; // 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);

        // 默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = getUploadFilesPath(suffix);
        try {
            byte[] uploadBytes = file.getBytes();
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                uploadManager.put(byteInputStream, key, upToken, null, null);
            } catch (QiniuException ex) {
                throw new BadRequestException(CommonConstants.KeyError);
            }
        } catch (UnsupportedEncodingException | BadRequestException ex) {
            throw new BadRequestException(CommonConstants.KeyError);
        }
        // 拼接路径地址
        String fileUrl = String.format("%s/%s", path, key);

        return fileUrl;
    }

    /**
     * 从七牛云删除文件
     * @param fileName 删除文件
     * @return 返回文件的删除结果
     * @Author zhangzikang
     * @Date 2023/8/13 8:54
     */
    public void delFile(String fileName) throws BadRequestException {
        // 判断文件路径是否为空。
        if(fileName.isEmpty()){
            throw new BadRequestException(CommonConstants.FileIsEmpty);
        }

        // 截取字符串长度
        String substring = fileName.substring(path.length()+1);

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            //单次批量请求的文件数量不得超过1000
            BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
            batchOperations.addDeleteOp(bucket, substring);
            Response response = bucketManager.batch(batchOperations);
            int status = response.statusCode;
            // 判断上传状态是否成功
            if (status != CommonConstants.status) {
                throw new BadRequestException(CommonConstants.DeleteFailed);
            }
        } catch (QiniuException ex) {
            throw new BadRequestException(CommonConstants.KeyError);
        }
    }

    /**
     * 上传文件并返回路径
     * @param
     * @param
     * @return
     * @Author zhangzikang
     * @Date 2023/8/13 8:54
     * @throws IOException
     */
    /*public String getFile(String suffix,MultipartFile file) throws IOException, BadRequestException {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;//指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = getUploadFilesPath(suffix);
        try {
            byte[] uploadBytes = file.getBytes();
            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                uploadManager.put(byteInputStream, key, upToken, null, null);
            } catch (QiniuException ex) {
                throw new BadRequestException(CommonConstants.KeyError);
            }
        } catch (UnsupportedEncodingException | BadRequestException ex) {
            throw new BadRequestException(CommonConstants.KeyError);
        }
        // 拼接路径地址
        String fileUrl = String.format("%s/%s", path, key);
        return fileUrl;
    }*/

    // 将图片路径转换为 MultipartFile 对象的辅助方法
/*    public MultipartFile convertToMultipartFile(String imagePath) throws IOException {
        File file = new File(imagePath);
        FileInputStream input = new FileInputStream(file);
        // 获取文件扩展名
        String extension = imagePath.substring(imagePath.lastIndexOf(".") + 1);
        // 根据文件扩展名确定 MIME 类型
        String contentType;
        switch (extension.toLowerCase()) {
            case "jpg":
                contentType = "image/jpg";
                break;
            case "jpeg":
                contentType = "image/jpeg";
                break;
            case "png":
                contentType = "image/png";
                break;
            case "gif":
                contentType = "image/gif";
                break;
            // 可以添加更多的图片格式
            default:
                throw new IllegalArgumentException("Unsupported file format");
        }

        // 返回 MultipartFile 对象
        return new MockMultipartFile(file.getName(), file.getName(), contentType, input);
    }
    // 上传图片到七牛云服务器
    public String uploadImage(MultipartFile file) throws IOException {
        String imageUrl = "http://" + path + "/" + file.getOriginalFilename(); // 假设这是七牛云返回的图片 URL
        return imageUrl;
    }

    // 修改 uploadImage 方法，接收文件路径作为参数
    public String uploadImage(String imagePath) throws IOException {
        // 将图片路径转换为 MultipartFile 对象
        MultipartFile file = convertToMultipartFile(imagePath);
        // 调用上传图片方法
        return uploadImage(file);
    }*/


    /**
     * 生成新的文件名
     * @return
     * @Author zhangzikang
     * @Date 2023/8/13 8:54
     */
    private final String getUploadFilesPath(String suffix){
        return datePath() + "/" + UUID.randomUUID().toString().replaceAll("-", "") + suffix;
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     * @Author zhangzikang
     * @Date 2023/8/13 8:54
     */
    private final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }
}
